package com.hgc.ch01.deadlock;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

/**
 * Created by 01367627 on 2019/6/14.
 */
public class ThreadDeadLockTest {

    private static Object art13 = new Object();
    private static Object art14 = new Object();

    static class James implements Runnable{
        public void run() {
            synchronized (art13){
                System.out.println(Thread.currentThread().getName() + " get art13");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (art14){
                    System.out.println(Thread.currentThread().getName() + " get art14");
                }
            }
        }
    }

    static class Lison implements Runnable{
        public void run() {
            synchronized (art14){
                System.out.println(Thread.currentThread().getName() + " get art14");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (art13){
                    System.out.println(Thread.currentThread().getName() + " get art13");
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread james = new Thread(new James());
        james.setName("James");
        Thread lison = new Thread(new Lison());
        lison.setName("Lison");
        james.start();
        lison.start();
        Thread.sleep(4000);
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        long[] deadlockedThreads = threadMXBean.findMonitorDeadlockedThreads();
        for(long threadId : deadlockedThreads){
            ThreadInfo threadInfo = threadMXBean.getThreadInfo(threadId);
            System.out.println("死锁线程名称：" + threadInfo.getThreadName());
            System.out.println("死锁线程状态：" + threadInfo.getThreadState());
            System.out.println("-----------------");
        }
    }

}
